<template>
  <!-- 上滑刷新 -->
  <div class="_load">
    <div class="text-center rem-24px c-99 line-height-50">
      <div v-if="datamore_">加载更多</div>
      <div v-if="datafail_">加载失败</div>
      <div v-if="dataing_">加载中</div>
      <div v-if="nodata_">没有更多了</div>
    </div>
  </div>
</template>

<script>
// 传两个值 list ， total 
// 当有total没有变动=有新数据  变动=没有数据
// 选项卡切换时 在外面代码将list清空
// 因为接口并不返回一个请求时会变化的字段 所以自己建了一个total变量来判断是否下一页数据为0。
export default {
  props: {
    datamore: {
      type: Boolean,
      default: true
    },
    datafail: {
      type: Boolean,
      default: false
    },
    dataing: {
      type: Boolean,
      default: false
    },
    nodata: {
      type: Boolean,
      default: false
    },
    list: {
      type: Array
    },
    total: {
      type: Number
    }
  },
  data() {
    return {
      list_: this.list,
      total_: this.total,
      datamore_: this.datamore,
      datafail_: this.datafail,
      dataing_: this.dataing,
      nodata_: this.nodata,
      timeType: false,
      time: 1,
      downup: "",
      page: 1
    };
  },
  watch: {
    datamore(n) {
      this.datamore_ = n;
    },
    datafail(n) {
      this.datafail_ = n;
    },
    dataing(n) {
      this.dataing_ = n;
    },
    nodata(n) {
      this.nodata_ = n;
    },
    list(n) {
      this.list_ = n;
    },
    total(n, o) {
      if (n != o) {
        this.nodata_ = true;
        this.datamore_ = false;
      }
    }
  },
  mounted() {
    window.addEventListener("scroll", () => {
      this.load();
    });
    if(this.list.length < 10){
      this.nodata_ = true;
      this.datamore_ = false;
    }
  },
  methods: {
    load() {
      let scrollTop =
        document.documentElement.scrollTop ||
        window.pageYOffset ||
        document.body.scrollTop; // 滚动的距离
      let viewHeight = document.documentElement.clientHeight; // 可视区域高度
      let offsetHeight = document.body.scrollHeight; // 总高度
      // console.log(viewHeight + scrollTop,offsetHeight)
      var scroll = scrollTop - this.downup;
      this.downup = scrollTop;
      if (scroll > 0) {
        // 是否上滑
        if (viewHeight + scrollTop >= offsetHeight - 0.8) {
          if (this.timeType) {
            return false;
          } else {
            // 2秒内请求一次
            // if(!this.datamore_){
            //   console.log('没数据了')
            //   return false
            // }
            console.log("加载");
            this.page++;
            this.$emit("loadData", this.page);
            this.timeType = true;
            let getTime = setInterval(() => {
              clearInterval(getTime);
              this.timeType = false;
            }, 2000);
          }
        }
      }
    }
  }
};
</script>

<style scoped>
._load .line-height-50 {
  height: 0.5rem;
  line-height: 0.5rem;
}
</style>